//
//  ClubSquareDatailViewController.swift
//  77Club
//
//  Created by Apple on 2024/9/5.
//

import UIKit
import ZLPhotoBrowser
import Photos

private let headerID    = "ClubSquareDetailTitleHeaderView"

class ClubSquareDatailViewController: ClubBaseViewController, RaeAnimationProtocol {
    
    private var navView = ClubSquareDatailNavView()
    private lazy var tableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .grouped)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = "#F7F8FA".toColor
        tableView.showsVerticalScrollIndicator = false
        tableView.register(ClubSquareDetailTopCell.self,ClubSquareForumCell.self,ClubSquareForumEmptyCell.self)
        tableView.register(ClubSquareDetailTitleHeaderView.self, forHeaderFooterViewReuseIdentifier: headerID)
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.separatorStyle = .none
        tableView.estimatedRowHeight = 100.0.Scale
        tableView.layer.cornerRadius = 12.0.Scale
        tableView.layer.masksToBounds = true
//        tableView.estimatedSectionHeaderHeight = 0
        tableView.sectionFooterHeight = 0
        tableView.contentInset = UIEdgeInsets.zero
        tableView.sectionHeaderTopPadding = 0
        return tableView
    }()
    var communityId: String = "" {
        didSet{
            loadData()
            loadPostList()
        }
    }
    private var model: ClubGameCommunityModel?
    private var topModels: [ClubGameCommunityListModel]?
    private var dataSource: [ClubGameCommunityListModel]?
    private var pageIndex = 1
    // type : 4=帖子 3=攻略 5=官方 7=活动
    private var type = "4"
    private var sortby = "1"
    let navH = CGFloat.navi_height + 200.0.Scale
    let tableViewTop = CGFloat.navi_height + 110.0.Scale
    let topH = (CGFloat.navi_height + 118.0.Scale) - .navi_height - 12.0.Scale
    private var releaseButton = c_make_ex(UIButton.self)
        .image("Square_add").end()
    
    private var images: [UIImage] = []
    private var assets: [PHAsset] = []
    private var nextButton = c_make_ex(UIButton.self)
        .color(.white).font(16.font_semiBold).text("跳过").end()
    
    private var playingIndexPath: IndexPath?
    private var currentVC = true
    
    var joinBlock: ((_ isJoined: Bool, _ md: ClubGameCommunityModel) -> Void)?
    
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        if type == "3" || type == "4" {
            if let is_ban = model?.is_ban {
                if is_ban == 1 {
                    releaseButton.isHidden = true
                }else{
                    releaseButton.isHidden = false
                }
            }else{
                releaseButton.isHidden = false
            }            
        }  
        currentVC = true
        NotificationCenter.default.addObserver(self, selector: #selector(toPostDetailVC), name: .forumToGameDetailVC, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(toStrategyVC), name: .toStrategyDetailVC, object: nil)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if communityId.count > 0 {
            self.loadData()
        }
        nextButton.removeFromSuperview()
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        releaseButton.isHidden = true
        currentVC = false
        NotificationCenter.default.post(name: .stopForumAudioPlayer, object: nil)
        NotificationCenter.default.removeObserver(self)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.subviews{
            navView
            tableView
        }
        
        navView.leading(0).trailing(0).top(0).height(navH)
        tableView.leading(0).trailing(0).bottom(0).top(tableViewTop)
                
        tableView.refresh_loadMore {
            self.loadMoreData()
        }.refresh_pull {
            self.loadNewData()
        }
        
        navView.backBlock = {
            self.navigationController?.popViewController(animated: true)
        }
        navView.joinBlock = { isJoined, md in
            self.joinBlock?(isJoined, md)
        }
        navView.toManagerVCBlock = {
            if self.model?.my_role == 1 {
                //塔主
                let settingVC = ClubSquareSettingViewController()
                settingVC.communityId = self.communityId
//                settingVC.updateData = {
//                    self.loadData()
//                }
                self.navigationController?.pushViewController(settingVC, animated: true)
            }else if self.model?.my_role == 2 {
                //管理员
                let settingVC = ClubForumAdminSettingViewController()
                if let md = self.model?.perms {
                    settingVC.permModel = md
                }
                settingVC.communityId = self.communityId                
                self.navigationController?.pushViewController(settingVC, animated: true)
            }
        }
        navView.moreBlock = {
            let moreView = ClubForumShareView()
            moreView.copyShareBlock = { type in
                self.shareDetail(type: type, shareUrl: self.model?.share_url ?? "", titile: self.model?.name ?? "", content: ClubGlobalTool.shared.forumShareDes)
            }
            self.entryAnimate.animation(show: moreView)
        }
        navView.searchBlock = {   
            let searchVC = ClubForumSearchViewController()
            searchVC.model = self.model
            searchVC.communityId = self.communityId
            self.navigationController?.pushViewController(searchVC, animated: true)
        }
        navView.toInfoVC = {
            guard let md = self.model else { return }
            let infoVC = ClubEditSquareInfoViewController()
            infoVC.infoStr = md.content
            infoVC.communityId = self.communityId
            infoVC.isHiddenSend = true
//            if md.my_role == 3 {
//                infoVC.isHiddenSend = true
//            }else{
//                if md.my_role == 1 {
//                    infoVC.isHiddenSend = false
//                }else{
//                    if let perms = md.perms {
//                        if perms.perm_notice == 1 {
//                            infoVC.isHiddenSend = false
//                        }else{
//                            infoVC.isHiddenSend = true
//                        }
//                    }
//                }
//            }
            self.navigationController?.pushViewController(infoVC, animated: true)
        }
        navView.toNoticeVC = {
            guard let md = self.model else { return }
            let noticeVC = ClubEditSquareNoticeViewController()
            noticeVC.noticeStr = md.notice
            noticeVC.communityId = self.communityId
            noticeVC.isHiddenSend = true
//            if md.my_role == 3 {
//                noticeVC.isHiddenSend = true
//            }else{
//                if md.my_role == 1 {
//                    noticeVC.isHiddenSend = false
//                }else{
//                    if let perms = md.perms {
//                        if perms.perm_notice == 1 {
//                            noticeVC.isHiddenSend = false
//                        }else{
//                            noticeVC.isHiddenSend = true
//                        }
//                    }
//                }
//            }
            self.navigationController?.pushViewController(noticeVC, animated: true)
        }
        releaseButton.addTarget(self, action: #selector(clickAddButton), for: .touchUpInside)
        self.view.addSubview(releaseButton)
        let panGesture = UIPanGestureRecognizer(target: self, action:#selector(dragAction(gesture:)))
        releaseButton.addGestureRecognizer(panGesture)
        releaseButton.snp.makeConstraints { make in
            make.right.equalTo(0)
            make.width.equalTo(88.0.Scale)
            make.height.equalTo(88.0.Scale)
            make.bottom.equalTo(-CGFloat.tabBar_height)
        }
    }
        
    @objc private func toStrategyVC(){
        self.type = "3"
        self.releaseButton.isHidden = false
        self.loadNewData()
        guard let md = model else { return }
        var fenleiModels = [ClubGameCommunityFenLeiModel]()
        for i in 0..<md.fenlei.count {  // 不包含 5
            var md = md.fenlei[i]
            if md.type == "3" {
                md.isSel = true
            }else{
                md.isSel = false
            }
            fenleiModels.append(md)
        }
    }
    
    @objc private func toPostDetailVC(noti: Notification){
        
        if let newsID = noti.userInfo?["infoID"] as? String {
            self.toDetailVC(newId: newsID, uid: "0")
        }
    }
    
    private func toDetailVC(newId: String, uid: String){
        
        if uid != "0" {
            //用户
            let detailVC = ClubSquareForumDetailViewController()
            detailVC.postID = newId
            detailVC.pid = self.communityId
//            detailVC.gameModel = self.gameModel
            detailVC.communityModel = self.model
            detailVC.likeBlock = {
                self.loadNewData()
            }
            detailVC.updateDataBlock = {
                self.loadNewData()
            }
            self.navigationController?.pushViewController(detailVC, animated: true)
        }else{
            //官方
            let detailVC = ClubForumDetailViewController()
            detailVC.newId = newId
            detailVC.communityId = self.communityId
            detailVC.likeBlock = {
                self.loadNewData()
            }
            self.navigationController?.pushViewController(detailVC, animated: true)
        }
    }
}

//MARK: - UITableViewDelegate, UITableViewDataSource
extension ClubSquareDatailViewController: UITableViewDelegate, UITableViewDataSource {
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        let offsetY = scrollView.contentOffset.y
        if offsetY >= 0 {
//            tableView.backgroundColor = "#F7F8FA".toColor
            if offsetY <= topH {
                self.navView.topViewAlpha = 0
                tableView.topConstraint?.constant = tableViewTop - offsetY
                tableView.contentInset = UIEdgeInsets(top: offsetY, left: 0, bottom: 0, right: 0)
            }else{
                tableView.topConstraint?.constant = tableViewTop - topH
                self.navView.topViewAlpha = 1.0
            }
        }else{
            tableView.topConstraint?.constant = tableViewTop
//            tableView.backgroundColor = .clear
        }
        
        if offsetY == 0 {
            loadFirstVideo()
        }
        
        guard let visibleCells = tableView.visibleCells as? [ClubSquareForumCell] else { return }
        // 获取 TableView 的中心位置
        let tableViewCenter = tableView.bounds.size.height / 2 + tableView.contentOffset.y

        for cell in visibleCells {
            guard let indexPath = tableView.indexPath(for: cell) else { continue }
            let cellCenterY = cell.center.y
            if abs(cellCenterY - tableViewCenter) < 100 { // 设定 50 为接近程度的阈值
                if playingIndexPath != indexPath {
                    playingIndexPath = indexPath
                    cell.playVideo()  // 播放视频
                }
            } else {
                if playingIndexPath == indexPath {
                    cell.pauseVideo()  // 暂停视频
                    playingIndexPath = nil
                }
            }
        }
    }

    func numberOfSections(in tableView: UITableView) -> Int {

        if self.topModels?.count ?? 0 > 0 {
            return 2
        }
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        if self.topModels?.count ?? 0 > 0 && section == 0 {
            return 1
        }else {
            return dataSource?.count ?? 0
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if indexPath.section == 0 && self.topModels?.count ?? 0 > 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "ClubSquareDetailTopCell", for: indexPath) as! ClubSquareDetailTopCell
            cell.models = topModels
            cell.jumpToDetail = { newsId, uid in
                self.toDetailVC(newId: newsId, uid: uid)
            }
            return cell
        }else{
            if dataSource?.count == 0 {
                let cell = tableView.dequeueReusableCell(withIdentifier: "ClubSquareForumEmptyCell", for: indexPath) as! ClubSquareForumEmptyCell
                cell.titleString = "暂无帖子~"
                return cell
            }
            let cell = tableView.dequeueReusableCell(withIdentifier: "ClubSquareForumCell", for: indexPath) as! ClubSquareForumCell
            cell.model = dataSource?[indexPath.row]
//            cell.zanButtonClick = { postId in
//                self.likePost(ID: postId)
//            }
            cell.jumpToDetail = {postId, uid in
                self.toDetailVC(newId: postId, uid: uid)
            }
            cell.didSelectImage = { index,images in
                self.selectImage(index: index, images: images)
            }
            cell.didSelectVideo = { url in
                self.selectVideo(url: url)
            }
            cell.toGameDetailVC = { gid in
                let detailVC = ClubGameDetailViewController()
                detailVC.gameId = gid
                self.navigationController?.pushViewController(detailVC, animated: true)
            }
            cell.toTopicDetailVC = { topicId in
                let detailVC = ClubTopicDetailViewController()
                detailVC.topicId = topicId
                self.navigationController?.pushViewController(detailVC, animated: true)
            }
            cell.showMoreView = { md in
                if (md.uid == "0" || md.uid.count == 0) && (self.model?.my_role != 2 && self.model?.my_role != 3){
                    let moreView = ClubForumShareView()
                    moreView.copyShareBlock = { type in
                        self.shareDetail(type: type, model: md)
                    }
                    self.entryAnimate.animation(show: moreView)
                }else{
                    self.showMoreView(md: md)
                }
            }
            cell.otherUserInfoVC = { uid in
                if uid.count > 0 {
                    if let user_id = UserDefaultsManager.getString(forKey: .uid), user_id.count > 0, user_id == uid {
                        let otherVC = ClubMineInfoViewController()
                        self.navigationController?.pushViewController(otherVC, animated: true)
                    }else{
                        let otherVC = ClubOtherInfoViewController()
                        otherVC.uid = uid
                        otherVC.updateBlock = {
                            self.loadNewData()
                        }
                        self.navigationController?.pushViewController(otherVC, animated: true)
                    }
                }                
            }
            
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        //帖子
        if (self.topModels?.count ?? 0 > 0 && indexPath.section == 1) || (self.topModels?.count ?? 0 <= 0 && indexPath.section == 0) {
            let newId = self.dataSource?[indexPath.row].id ?? ""
            let uid = self.dataSource?[indexPath.row].uid ?? "0"
            self.toDetailVC(newId: newId, uid: uid)
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
//        return UITableView.automaticDimension
        if indexPath.section == 0 && self.topModels?.count ?? 0 > 0 {
            return UITableView.automaticDimension
        }else{
            if dataSource?.count == 0 {
                return UITableView.automaticDimension
            }
            if let md = dataSource?[indexPath.row]{
                let time = ClubGlobalTool.shared.timeDescription(from: md.time, 2)
                if time == "刚刚" {
                    var height = 113.0.Scale
                    var content = md.content + " "
                    if md.content_h5.count > 0 {
                        content = md.content_h5 + " "
                    }
                    height += content.calculateTextHeight(font: 15.font_regular!, width: CGFloat.screenWidth - 104.0.Scale) + 8.0.Scale
                    
                    if md.video.count > 0 || md.image.count == 1{
                        height += 152.0.Scale
                    }else if md.image.count == 2 {
                        height += 85.0.Scale + 44.0.Scale
                    }else if md.image.count > 2 {
                        let w = (CGFloat.screenWidth - 110.0.Scale)/3
                        if md.image.count == 3 || md.image.count == 4 || md.image.count == 5 {
                            height += w
                        }else if md.image.count == 6 || md.image.count == 7 || md.image.count == 8 {
                            height += w * 2 + 2
                        }else{
                            height += w * 3 + 4
                        }
                    }
                    height += 74.0.Scale
                    
                    return height
                }
                
            }
            
            return UITableView.automaticDimension
        }
    }

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        if (self.topModels?.count ?? 0 > 0 && section == 1) || (self.topModels?.count ?? 0 == 0 && section == 0) {
            let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: headerID) as! ClubSquareDetailTitleHeaderView
            header.sortBy = self.sortby
            header.updateData = { type in
                DispatchQueue.main.async {
                    NotificationCenter.default.post(name: .stopForumAudioPlayer, object: nil)
                }
                self.sortby = type
                self.loadNewData()
            }
            return header
        }
        let header = UIView()
        header.backgroundColor = .clear
        return header
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        
        if self.topModels?.count ?? 0 > 0 && section == 1 {
            return 44.0.Scale
        }else if self.topModels?.count ?? 0 == 0 && section == 0 {
            return 44.0.Scale
        }
        return 12.0.Scale
    }
    
    private func selectImage(index: Int, images: [String]) {
        
        var datas: [Any] = []
        for a in images {
            datas.append(URL(string: a)!)
        }
        let vc = ZLImagePreviewController(datas: datas, index: index, showSelectBtn: false,showBottomView: false) { (url) -> ZLURLType in
            
            return .image
        } urlImageLoader: { (url, imageView, progress, loadFinish) in
            imageView.kf.setImage(with: url) { (receivedSize, totalSize) in
                let percentage = (CGFloat(receivedSize) / CGFloat(totalSize))
                debugPrint("\(percentage)")
                progress(percentage)
            } completionHandler: { (_) in
                loadFinish()
            }
        }
        
        vc.doneBlock = { (datas) in
            debugPrint(datas)
        }
        
        vc.modalPresentationStyle = .fullScreen
        self.showDetailViewController(vc, sender: nil)
    }
    
    private func selectVideo(url: String) {
        
        let vc = ZLImagePreviewController(datas: [URL(string: url)!], index: 0, showSelectBtn: false,showBottomView: false) { (url) -> ZLURLType in
            
            return .video
        } urlImageLoader: { (url, imageView, progress, loadFinish) in
            imageView.kf.setImage(with: url) { (receivedSize, totalSize) in
                let percentage = (CGFloat(receivedSize) / CGFloat(totalSize))
                debugPrint("\(percentage)")
                progress(percentage)
            } completionHandler: { (_) in
                loadFinish()
            }
        }
        
        vc.doneBlock = { (datas) in
            debugPrint(datas)
        }
        
        vc.modalPresentationStyle = .fullScreen
        self.showDetailViewController(vc, sender: nil)
    }
    
    private func shareDetail(type: Int, shareUrl: String, titile: String, content: String) {
        if type == 3 {
            ClubGlobalTool.shared.shareToQQ(title: titile, description: content, imageUrl: "https://www.77.top/static/ios_logo.jpg", url: shareUrl)
        }else if type == 4 {
            "分享口令已复制成功".toast_success
            UIPasteboard.general.string = shareUrl
        }else{
            ClubGlobalTool.shared.shareToWechat(title: titile, des: content, image: "AppIcon".toImage!, shareUrl: shareUrl, shareType: type)
        }
    }
}

//MARK: action
extension ClubSquareDatailViewController {
    
    @objc private func dragAction(gesture: UIPanGestureRecognizer) {
        
        // 移动状态
        let moveState = gesture.state
        switch moveState {
        case .began:
            break
        case .changed:
            // floatBtn 获取移动轨迹
            let point = gesture.translation(in: self.view)
            self.releaseButton.center = CGPoint(x: self.releaseButton.center.x + point.x, y: self.releaseButton.center.y + point.y)
            break
        case .ended:
            // floatBtn 移动结束吸边
            let point = gesture.translation(in: self.view)
            var newPoint = CGPoint(x: self.releaseButton.center.x +  point.x, y: self.releaseButton.center.y + point.y)
            if newPoint.x < .screenWidth / 2.0 {
                newPoint.x = self.releaseButton.bounds.width/2 + 17.0.Scale
            } else {
                newPoint.x = .screenWidth - self.releaseButton.bounds.width/2 - 17.0.Scale
            }
            if newPoint.y <= self.releaseButton.bounds.height/2 + 17.0.Scale + .navi_height{
                newPoint.y = self.releaseButton.bounds.height/2 + 17.0.Scale + .navi_height
            } else if newPoint.y >= self.view.bounds.height - self.releaseButton.bounds.height/2 - 17.0.Scale {
                newPoint.y = self.view.bounds.height - self.releaseButton.bounds.height/2 - 17.0.Scale
            }
            // 0.5秒 吸边动画
            UIView.animate(withDuration: 0.5) {
                self.releaseButton.center = newPoint
            }
            break
        default:
            break
        }
        // 重置 panGesture
        gesture.setTranslation(.zero, in: self.view)
    }
    
    @objc private func clickAddButton() {

        if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
            let pushView = ClubSquareDatailPushView()
            pushView.toNextVC = { type in
                //type 0=草稿 1=图片 2=视频
                if type == 0 {
                    let draftVC = ClubDraftViewController()
                    draftVC.communityId = self.communityId
                    draftVC.updateDataBlock = {
                        self.sortby = "0"
                        self.loadNewData()
                    }
                    self.navigationController?.pushViewController(draftVC, animated: true)
                }else{
                    self.checkPhotoLibraryPermission(type: type)
                }
                
            }
            self.entryAnimate.animation(show: pushView)
        }else{
            self.navigationController?.pushViewController(ClubLoginViewController(), animated: true)
        }
    }
    
    //==============imgagePicker===============
    //检查相册权限
    private func checkPhotoLibraryPermission(type: Int) {
         let status = PHPhotoLibrary.authorizationStatus()
             
         switch status {
             case .authorized:
                 // 已经授权，继续访问相册
             DispatchQueue.main.async {
                 self.showPhotoLibrary(type: type)
             }
                 
             case .denied, .restricted:
                 // 用户拒绝或受限，无法访问相册
                 print("用户拒绝访问相册")
             case .notDetermined:
                 // 用户还没有决定是否允许访问，进行请求
                 PHPhotoLibrary.requestAuthorization { newStatus in
                     if newStatus == .authorized {
                         // 用户授权，继续访问相册
                         DispatchQueue.main.async {
                             self.showPhotoLibrary(type: type)
                         }
                     } else {
                         print("用户拒绝访问相册")
                     }
                 }
         @unknown default:
                 print("未知的权限状态")
         }
     }
    
    private func showPhotoLibrary(type: Int) {
        
        let config = ZLPhotoConfiguration.default()
        
        config.languageType = .chineseSimplified
        config.allowSelectGif = false
        config.allowMixSelect = false
        config.allowTakePhotoInLibrary = true
        config.allowEditVideo = true
        config.maxEditVideoTime = .max
        config.maxRecordDuration = .max
        config.maxSelectVideoDuration = .max
        config.saveNewImageAfterEdit = false
        config.editAfterSelectThumbnailImage = true
        config.allowSelectOriginal = false
        config.animateSelectBtnWhenSelect = false
        config.cropVideoAfterSelectThumbnail = true
        config.saveNewImageAfterEdit = false
        config.colorConfiguration.previewBtnTitleColor = "#FD8B00".toColor
        config.colorConfiguration.bottomToolViewBtnNormalBgColor = "#FD8B00".toColor
        config.colorConfiguration.selectMorePhotoWhenAuthIsLismitedTitleColor = "#FD8B00".toColor
        
        if type == 1 {
            //图片
            config.allowSelectImage = true
            config.maxSelectCount = 9
            config.allowSelectVideo = false
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                self.addSkipButton()
            }

        }else{
            config.maxSelectCount = 0
            config.allowSelectVideo = true
            config.allowSelectImage = false
        }
        
        let ac = ZLPhotoPreviewSheet()
        
        ac.selectImageBlock = { [weak self] (images, assets, isOriginal) in
            guard let self = self else { return }
            self.images = images
            self.assets = assets
            let pushVC = ClubPushForumViewController()
            pushVC.type = type
            pushVC.communityId = self.communityId
            pushVC.images = images
            pushVC.assets = assets
            pushVC.updateDataBlock = {
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                    self.sortby = "0"
                    self.loadNewData()
                }
            }
            
            self.present(pushVC, animated: true)
        }
        ac.showPhotoLibrary(sender: self)
    }
    
    private func addSkipButton() {
        
        guard let window = UIApplication.shared.connectedScenes
                        .compactMap({ $0 as? UIWindowScene })
                        .first?.windows.first else {
            print("无法找到主窗口")
            return
        }

        if traitCollection.userInterfaceStyle == .dark {
            // 当前是暗黑模式
            nextButton.setTitleColor("#F7F8FA".toColor, for: .normal)
        } else {
            nextButton.setTitleColor(.white, for: .normal)
        }
        nextButton.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
        window.addSubview(nextButton)
        nextButton.snp.makeConstraints { make in
            make.width.equalTo(56)
            make.height.equalTo(44)
            make.top.equalToSuperview().offset(CGFloat.statusHeight)
            make.trailing.equalToSuperview()
        }
        window.bringSubviewToFront(nextButton)
    }
    
    @objc private func buttonTapped() {
        // 跳转或关闭逻辑
        nextButton.removeFromSuperview()
        self.dismiss(animated: true){
            let pushVC = ClubPushForumViewController()
            pushVC.type = 1
            pushVC.communityId = self.communityId
            
            self.present(pushVC, animated: true)
        }
    }
    
    private func showMoreView(md: ClubGameCommunityListModel){
        
        if md.status != 1 {
            let delView = ClubForumShareDelView()
            delView.delBlock = {
                Task{
                    let res = await self.network.request(.delPost(postID: md.id))
                    if res.isSuccess {
                        "删除成功".toast_success
                        self.loadPostList()
                    }
                }
            }
            self.entryAnimate.animation(show: delView)
        }else{
            let moreView = ClubMoreView()
            var dataArr = [ClubMoreModel]()
            if self.model?.my_role == 1 {
                if md.is_best == 1 {
                    let mod = ClubMoreModel(title: "取消置顶此帖子",img: "ForumDetail_cancelTop",isRed: false,type: 2)
                    dataArr.append(mod)
                }else{
                    let mod = ClubMoreModel(title: "置顶此帖子",img: "ForumDetail_top",isRed: false,type: 1)
                    dataArr.append(mod)
                }
                if let uid = UserDefaultsManager.getString(forKey: .uid), uid == md.uid_des {
                    let delModel = ClubMoreModel(title: "删除此帖子", img: "Home_more_del", isRed: true,type: 4)
                    dataArr.append(delModel)
                }else{
                    let mod = ClubMoreModel(title: "下架此帖子",img: "ForumDetail_down",isRed: false,type: 3)
                    dataArr.append(mod)
                }
                moreView.dataSource = dataArr
            }else if self.model?.my_role == 2{
                    
                if self.model?.perms?.perm_top == 1 {
                    if md.is_best == 1 {
                        let mod = ClubMoreModel(title: "取消置顶此帖子",img: "ForumDetail_cancelTop",isRed: false,type: 2)
                        dataArr.append(mod)
                    }else{
                        let mod = ClubMoreModel(title: "置顶此帖子",img: "ForumDetail_top",isRed: false,type: 1)
                        dataArr.append(mod)
                    }
                }
                if self.model?.perms?.perm_off == 1 {
                    if let uid = UserDefaultsManager.getString(forKey: .uid), uid == md.uid_des {
                        let delModel = ClubMoreModel(title: "删除此帖子", img: "Home_more_del", isRed: true,type: 4)
                        dataArr.append(delModel)
                    }else{
                        let mod = ClubMoreModel(title: "下架此帖子",img: "ForumDetail_down",isRed: false,type: 3)
                        dataArr.append(mod)
                    }
                }else{
                    if let uid = UserDefaultsManager.getString(forKey: .uid), uid == md.uid_des {
                        let delModel = ClubMoreModel(title: "删除此帖子", img: "Home_more_del", isRed: true,type: 4)
                        dataArr.append(delModel)
                    }
                }
                    
                moreView.dataSource = dataArr
            }else{
                    
                moreView.isPost = true
                moreView.uid_des = md.uid_des
            }

            moreView.reportBlock = {
                if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
                    let reportVC = ClubReportViewController()
                    reportVC.dynamicID = md.id
                    reportVC.type = "0"
                    reportVC.isShequ = true
//                    reportVC.updateDataBlock = {
//                        self.navigationController?.popViewController(animated: true)
//                    }
                    self.present(reportVC, animated: true)
                }else{
                    //登录
                    self.navigationController?.pushViewController(ClubLoginViewController(), animated: true)
                }
            }
            moreView.delBlock = {
                Task{
                    let res = await self.network.request(.delPost(postID: md.id))
                    if res.isSuccess {
                        "删除成功".toast_success
                        self.loadPostList()
                    }
                }
            }
            moreView.copyShareBlock = { type in
                self.shareDetail(type: type, model: md)
            }
            moreView.moreBlock = { type in
                if type == 3 {
                    //下架
                    Task {
                        let res = await self.network.request(.postUpOrDown(id: md.id))
                        if res.isSuccess {
                            self.loadPostList()
                            self.navigationController?.popViewController(animated: true)
                        }
                    }
                }else{
                    //置顶或者取消置顶
                    Task {
                        let res = await self.network.request(.postTopOrDown(id: md.id))
                        if res.isSuccess {
                            self.loadPostList()
                        }
                    }
                }
            }
            self.entryAnimate.animation(show: moreView)
        }
        
    }
    
    private func shareDetail(type: Int, model: ClubGameCommunityListModel) {
        if type == 3 {
            ClubGlobalTool.shared.shareToQQ(title: ClubGlobalTool.shared.postShareTitle, description: model.title, imageUrl: "https://www.77.top/static/ios_logo.jpg", url: model.share_url)
        }else if type == 4 {
            "分享口令已复制成功".toast_success
            let shareUrl = self.model?.share_url ?? ""
            UIPasteboard.general.string = shareUrl
        }else{
            ClubGlobalTool.shared.shareToWechat(title: ClubGlobalTool.shared.postShareTitle, des: model.title, image: "AppIcon".toImage!, shareUrl: model.share_url, shareType: type)
        }
    }
}


//MARK: data
extension ClubSquareDatailViewController {
    
    private func loadData(){
        Task {
            ToastUtil.show()
            let res = await network.request(.communityTop(communityID: communityId),type: ClubGameCommunityModel.self)
            ToastUtil.dismiss()
            if res.isSuccess, let model = res.model {
                
                self.navView.model = model
                self.navView.communityId = communityId
                self.model = model
            }
        }
    }
    
    private func loadPostList(){
        
        Task {
            let res = await network.requestMoreData(.communityPostList(communityID: communityId, type: self.type, sortby: self.sortby, page: pageIndex),type: ClubSquareDetailPostModel.self)
            tableView.refresh_end()
            ToastUtil.dismiss()
            if res.isSuccess, let data = res.model?.data {
                self.dataSource = data
                self.topModels = res.model?.bests
                tableView.reloadData()
                self.loadFirstVideo()
            }
        }
    }
    
    @objc func loadNewData(){
        ToastUtil.show()
        pageIndex = 1
        loadPostList()
    }
    
    @objc func loadMoreData(){

        pageIndex += 1
        Task {
            let res = await network.requestMoreData(.communityPostList(communityID: communityId, type: self.type, sortby: self.sortby, page: pageIndex),type: ClubSquareDetailPostModel.self)
            tableView.refresh_end()
            ToastUtil.dismiss()
            if res.isSuccess, let data = res.model?.data {
                if data.count > 0 {
                    self.dataSource?.append(contentsOf: data)
                }else{
                    tableView.refresh_end(true)
                }                
                tableView.reloadData()
            }
        }
    }
    
//    private func likePost(ID: String){
//        if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
//            Task{
//                ToastUtil.show()
//                let _ = await self.network.request(.likeStrategyPost(pid: ID, puid: "", type: "0"))
//                ToastUtil.dismiss()
//                "点赞成功".toast_success
//                self.loadPostList()
//            }
//        }else{
//            self.navigationController?.pushViewController(ClubLoginViewController(), animated: true)
//        }
//        
//    }
    
    private func loadFirstVideo(){
        
        if currentVC && self.dataSource?.count ?? 0 > 0 {
            let md = self.dataSource?[0]
            if md?.video.count ?? 0 > 0 {
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                    var section = 0
                    if self.topModels?.count ?? 0 > 0 {
                        section = 1
                    }
                    let indexPath = IndexPath(row: 0, section: section)
                    self.playingIndexPath = indexPath
                    if let cell = self.tableView.cellForRow(at: indexPath) as? ClubSquareForumCell {
                        cell.playVideo()  // 播放视频
                    }
                }
            }
        }
    }
}
